package idv.jieh.commons.io;

import java.io.*;

public class ObjectKeeper {
  private final static String default_keep_path = "data/";

  private String keep_path;

  public ObjectKeeper(){ this(default_keep_path); }

  public ObjectKeeper(String path) {
//    keep_path = path + path.endsWith("/");
    keep_path = path;
    File folder_data = new File(keep_path);
    if(!folder_data.exists()){
      folder_data.mkdir();
    }
  }

  private File getFile(String file_name){
    File r = new File(keep_path + file_name + ".j");
    if(!r.exists()){
      try {
        r.createNewFile();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    return r;
  }

  // 儲存物件
  public void writeObject(Object obj){
    String className = getName(obj.getClass().getName());
    try {
      java.io.FileOutputStream fos = new java.io.FileOutputStream(getFile(className));
      java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(fos);
      oos.writeObject(obj);
      oos.close();
    } catch (FileNotFoundException ex) {
      ex.printStackTrace();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  // 開啟物件
  public Object readObject(String className) {
    String object_name = getName(className);

    Object obj = null;

    try{
      try {
        java.io.FileInputStream fis = new java.io.FileInputStream(getFile(object_name));
        java.io.ObjectInputStream ois = new java.io.ObjectInputStream(fis);
        obj = ois.readObject();
      }catch (EOFException ex){
        try {
          obj = Class.forName(className).newInstance();
        } catch (IllegalAccessException ex1) {
          ex1.printStackTrace();
        } catch (InstantiationException ex1) {
          ex1.printStackTrace();
        }
      }catch (IOException ex) {
        ex.printStackTrace();
      }
    }catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }

    return obj;
  }

  private String getName(String className){
    return className.substring(className.lastIndexOf(".")+1, className.length());
  }

}
